using MediatR;
using Microsoft.Extensions.Logging;
using RBAC.Domain.ProcessManagement;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Write.Api.Application.Command.ProcessManagements;

namespace RBAC.Write.Api.Application.Handler.ProcessManagements
{
    /// <summary>
    /// 批量删除工艺流程（逻辑删除）处理器
    /// </summary>
    public class BatchDeleteProcessFlowsHandler : IRequestHandler<BatchDeleteProcessFlowsCommand, APIResult<int>>
    {
        private readonly IBaseRepository<ProcessFlow> _flowRepo;
        private readonly IBaseRepository<ProcessFlowDetail> _detailRepo;
        private readonly IBaseRepository<ProcessFlowAttachment> _attachRepo;
        private readonly ILogger<BatchDeleteProcessFlowsHandler> _logger;

        public BatchDeleteProcessFlowsHandler(
            IBaseRepository<ProcessFlow> flowRepo,
            IBaseRepository<ProcessFlowDetail> detailRepo,
            IBaseRepository<ProcessFlowAttachment> attachRepo,
            ILogger<BatchDeleteProcessFlowsHandler> logger)
        {
            _flowRepo = flowRepo;
            _detailRepo = detailRepo;
            _attachRepo = attachRepo;
            _logger = logger;
        }

        public Task<APIResult<int>> Handle(BatchDeleteProcessFlowsCommand request, CancellationToken cancellationToken)
        {
            var res = new APIResult<int>();
            try
            {
                if (request.Ids == null || request.Ids.Count == 0)
                {
                    res.Code = APIEnums.Error;
                    res.Msg = "请选择要删除的记录";
                    return Task.FromResult(res);
                }

                // 仅对主表逻辑删除，明细/附件可按业务选择是否同步软删；此处一并软删
                var delMain = _flowRepo.Execute("UPDATE ProcessFlow SET IsDeleted=1 WHERE Id IN @Ids AND IsDeleted=0", new { Ids = request.Ids });
                _detailRepo.Execute("UPDATE ProcessFlowDetail SET IsDeleted=1 WHERE FlowId IN @Ids AND IsDeleted=0", new { Ids = request.Ids });
                _attachRepo.Execute("UPDATE ProcessFlowAttachment SET IsDeleted=1 WHERE FlowId IN @Ids AND IsDeleted=0", new { Ids = request.Ids });

                res.Code = APIEnums.Success;
                res.Data = delMain;
                res.Msg = "删除成功";
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量删除工艺流程失败: {Message}", ex.Message);
                res.Code = APIEnums.Error;
                res.Msg = "批量删除工艺流程异常";
                res.Data = 0;
            }
            return Task.FromResult(res);
        }
    }
}
